<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="商品名称">
              <a-input v-model="queryParam.goodsName" placeholder=""/>
            </a-form-item>
          </a-col>
          <a-col :md="!advanced && 8 || 24" :sm="24">
            <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
            <a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="$refs.addGoods.add()" v-if="tt==='1'">新建</a-button>
      <a-dropdown v-action:edit v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="remove">
            <remove-goods ref="removeGoods" :listIds="selectedRowKeys.join(',')" @ok="handleOk"/>
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作 <a-icon type="down" />
        </a-button>
      </a-dropdown>
      <a-dropdown  v-action:edit v-else-if="selectedRowKeys.length == 0">
        <a-button style="margin-left: 8px">
          批量操作<a-icon type="down" />
        </a-button>
      </a-dropdown>
    </div>

    <s-table
      ref="table"
      size="default"
      rowKey="key"
      :columns="columns"
      :data="loadData"
      :alert="options.alert"
      :rowSelection="options.rowSelection"
      showPagination="auto"
    >
      <span slot="desc" slot-scope="text, record">
        <template>
          <a @click="showInfo(record)" >显示详情</a>
        </template>
      </span>
      <span slot="num" slot-scope="text, record">
        <template>
          <a @click="showDetail(record)">{{record.goodsNum}}</a>
        </template>
      </span>
      <span slot="action" slot-scope="text, record">
        <template>
          <a @click="handleEdit(record)" >编辑</a>

          <a-divider type="vertical" />
            <a-popconfirm
              :title="title"
              @confirm="delay(record)"
              okText="是"
              cancelText="否"
            >
            <a :disabled="record.goodsStatus===1">上架</a>
            </a-popconfirm>
          <a-divider type="vertical" />
          <remove-goods ref="removeGoods" :listIds="String(record.listId)" :data2="data2" @ok="handleOk"/>
        </template>
      </span>

    </s-table>
    <add-goods ref="addGoods" @ok="handleOk" />
    <edit-goods ref="editGoods" @ok="handleOk"/>
    <ShowInfo ref="showInfo" @ok="handleOk"/>
    <ShowDetail ref="showDetail" @ok="handleOk"/>
  </a-card>
</template>

<script>
// import moment from 'moment'
import { STable } from '@/components'
import {addAll} from '@/api/basic/goods'
import {queryGoods,editGoodsStatus} from '@/api/basic/goodsList'
import { queryUser } from '@/api/basic/user'
import ShowInfo from './modules/goods/showInfo'
import ShowDetail from './modules/goods/showDetail'
import AddGoods from './modules/goods/AddGoods'
import EditGoods from './modules/goods/EditListGoods'
import RemoveGoods from './modules/goods/RemoveListGoods'
// 用于处理过滤器动态获取数据

export default {
  name: 'GoodsList',
  components: {
    ShowDetail,
    STable,
    AddGoods,
    EditGoods,
    RemoveGoods,
    ShowInfo
  },
  data() {
    return {
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      userInfo: {},
      tt: this.$store.getters.roles.id,
      userId: this.$store.getters.userInfo.id,
      data2: [],
      expandedKeys: [1],
      treeData: [],
      nftValue: {},
      dataList: [],
      // 表头
      columns: [
        {
          title: '商品Id',
          dataIndex: 'key',
          align: 'center'
        },
        {
            title: '商品名称',
            dataIndex: 'goodsName',
            align: 'center'
          },
          {
            title: '藏品数量',
            dataIndex: 'num',
            align: 'center',
            scopedSlots: {customRender: 'num'}
          },
          {
            title: '所属学院',
            dataIndex: 'unitName',
            align: 'center',
            // scopedSlots: {customRender: 'goodsUnit'}
          },
          {
            title: '创造者',
            dataIndex: 'goodsCreator',
            align: 'center',
          },
          {
            title: '创造时间',
            dataIndex: 'createTime',
            align: 'center',
          },
          {
            title: '发布时间',
            dataIndex: 'showTime',
            align: 'center',
          },
        {
          title: '发布时间',
          dataIndex: 'showTime',
          align: 'center',
        },
          {
            title: '商品详情',
            dataIndex: 'desc',
          align: 'center',
          scopedSlots: {customRender: 'desc'}
        },
        {
          title: '操作',
          width:'200px',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: {customRender: 'action'}
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        console.log("biO1")
        console.log(parameter)
        // 统一处理查询参数，便于后端表格DTO用固定参数接收
        const queryJson = {'queryParam': JSON.stringify(this.queryParam)}
        console.log(queryJson)
        queryUser(Object.assign(parameter, queryJson))
          .then(res => {
            this.userInfo = res.result.data
            return res.result
          })
        return queryGoods(Object.assign(parameter, queryJson))
          .then(res => {
            console.log("ans")
            console.log(res)
            const _this = this
            // eslint-disable-next-line no-unused-vars
            this.data2 = res.result.data
            let count = 0
            if (_this.tt === '2') {
              // eslint-disable-next-line no-unused-vars
              this.data2 = res.result.data.filter(i => (i.userId === _this.userId) && (++count))
            }
            this.data2 = this.data2.filter(i=>(i.goodsCreator="宁小理"))
            this.data2 = this.data2.filter(i=>{
              if(i.goodsUnit==1){i.unitName="计算机与数据工程学院"}
              else if(i.goodsUnit==2){i.unitName="信息科学与工程学院"}
              else if(i.goodsUnit==3){i.unitName="机械工程与能源学院"}
              else if(i.goodsUnit==4){i.unitName="生物工程学院"}
              else if(i.goodsUnit==5){i.unitName="材料学院"}
              else if(i.goodsUnit==6){i.unitName="商学院"}
              else if(i.goodsUnit==7){i.unitName="传媒学院"}
              else if(i.goodsUnit==8){i.unitName="外语学院"}
              else if(i.goodsUnit==9){i.unitName="设计学院"}
              else if(i.goodsUnit==10){i.unitName="土建学院"}
              return i
            })
            console.log("unit"+this.data2[1].unitName)
            console.log(count)
            const use = this.userInfo
            res.result.data = this.data2
            if (count !== 0) {
              res.result.totalCount = count
            }
            console.log("这是data")
            console.log(res.result)
            return res.result
          })
      },
      selectedRowKeys: [],
      selectedRows: [],
      // custom table alert & rowSelection
      options: {
        alert: {
          show: true, clear: () => {
            this.selectedRowKeys = []
          }
        },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      optionAlertShow: true,
      title: '确定要上架此商品吗？',
    }
  },
  beforeCreate() {
  },
  created() {
  },
  methods: {
    delay(record) {
      var self = this
      var t
      clearTimeout(t)
      t = setTimeout(function() {
        record.goodsStatus = 1
        self.dataList = []
        self.$message.info('正在上架中，请稍等')
        for (let i = 0; i < record.goodsNum; i++) {
          console.log(record)
          let str = self.nft(record).split(',')
          console.log(str)
          let data = {}
          Object.assign(data, record)
          data.tokenId = str[1]
          data.owner = str[2]
          data.creator = str[3]
          self.dataList.push(data)
        }
        console.log(self.dataList)
        addAll(self.dataList)
          .then(res => {
            if (res.message !== 'error') {
              self.$message.success("上架成功")

            } else {
              self.visible = false
              self.confirmVisible = false
              self.$message.error('操作失败！')
            }
          })
        console.log("gost",record.listId)
        const status={listId:record.listId}
        editGoodsStatus(status)
          .then(res => {
            if (res.message !== 'error') {
              self.$message.success("状态更新成功")
            } else {
              self.$message.error('状态更新失败！')
            }
          })
        // window.eventHub.$emit('refreshList', '')// 更新右侧列表状态
      }, 4000)
    },
    // handleNFT(record) {
    //   record.goodsStatus = 1
    //   this.dataList = []
    //   this.$message.info('正在上架中，请稍等')
    //   for (let i = 0; i < record.goodsNum; i++) {
    //     console.log(record)
    //     let str = this.nft(record).split(',')
    //     console.log(str)
    //     let data = {}
    //     Object.assign(data, record)
    //     data.tokenId = str[1]
    //     data.owner = str[2]
    //     data.creator = str[3]
    //     this.dataList.push(data)
    //   }
    //   console.log(this.dataList)
    //   addAll(this.dataList)
    //     .then(res => {
    //       if (res.message !== 'error') {
    //         this.$message.success("上架成功")
    //
    //       } else {
    //         this.visible = false
    //         this.confirmVisible = false
    //         this.$message.error('操作失败！')
    //       }
    //     })
    //   console.log("gost",record.listId)
    //   const status={listId:record.listId}
    //   editGoodsStatus(status)
    //     .then(res => {
    //       if (res.message !== 'error') {
    //         this.$message.success("状态更新成功")
    //       } else {
    //         this.$message.error('状态更新失败！')
    //       }
    //     })
    //
    // },
    handleEdit(record) {
      console.log("测试33")
      console.log(record)
      this.$refs.editGoods.edit(record)
    },
    showInfo(record) {
      // console.log(record)
      this.$refs.showInfo.showInfo(record)
    },
    showDetail(record) {
      this.$refs.showDetail.showDetail(record)
    },
    handleOk() {
      this.$refs.table.clearSelected()
      this.$refs.table.refresh(false)
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    nft(record) {
      //function mint(string memory uri) public returns (uint256)  url为作品数据的保存路径, {from: web3.eth.accounts[0], gas: 2000000})暂时写死
      // console.log(this.$root.myContractInstance.Login('admin1qaz@wsx'));
      // 返回作品总数根据作品Id获取作品信息，作品Id从0开始累加
      console.log(1220)
      console.log(record.fileUrl)
      this.$root.myContractInstance.mint(record.photoUrl, {from: this.$root.userUrl, gas: 2000000})
      let result1 = this.$root.myContractInstance.currentId().toString();
      // 根据作品Id获取作品信息，作品Id从0开始累加
      let result = this.$root.myContractInstance.fetchWorksFromId(result1)
      // var result = myContractInstance.worksCount();
      // 返回某用户所有的作品Id
      //var result = myContractInstance.findWorksFromUser(web3.eth.accounts[0]);
      // 交易
      // function buyItem(workId, seller, buyer)
      // {
      //   var result = myContractInstance.buyItem(workId, buyer, {from: seller, gas: 2000000});
      //   return result;
      // }
      // var a = buyItem(1, web3.eth.accounts[0], web3.eth.accounts[3]);
      // console.log(a) ;
      // 删除作品, 查出来的Id=0就表示已经被删了，需要把返回数组中的0过滤掉。
      //var result = myContractInstance.burn(2, web3.eth.accounts[0], {from: web3.eth.accounts[1], gas: 2000000});
      console.log(result)
      return result.toString()
    }
  }
}
</script>
